var Game = {
    ws: null,
    url: '',
    timer: 0,
    reback_times: 3,
    holes: [],
    outs: [],
    debug: true,
    log: function(data){
        if (this.debug){
            console.log(data)
        }
    },
    start: function(url) {
        this.url = url;
        ws = new WebSocket(url);
        ws.binaryType = "arraybuffer";
        var obj = this;

        ws.onopen = function(evt) {
            clearInterval(obj.timer);
            obj.log('server connected');
            obj.log(evt);
            Req.heart(obj)

            user = User.getUser();
            if (user && user.id) {
                Req.reconnect(obj);
            }
        }

        ws.onclose = function(evt) {
            obj.timer = setInterval(function(){
                if (obj.reback_times == 0) {
                    clearInterval(obj.timer);
                    obj.timer = null;
                    $('#board').removeClass($('#board').attr('class')).addClass('login');
                } else {
                    obj.reback_times--;
                    obj.start(obj.url);
                }
            }, 5000);
            obj.log('server disconnected');
            obj.log(evt);
        }
        ws.onmessage = function(evt) {
            if (!evt.data) return;
            obj.log(evt);

            var total = new DataView(evt.data);
            var total_len = total.byteLength;
            if (total_len < 4) {
                obj.log('data error')
                //ws.close()
                return;
            }
            
            var off = 0
            var body = ''
            while(total_len > off) {
                var len = total.getUint32(off);
                var data = evt.data.slice(off, off + len + 4);
                body = Packet.unpack(data);
                obj.log(body)
                if (body.code == ErrorCode.SUCCESS) {
                    obj.receive(body.command, body.data)
                } else {
                    alert(body.message);
                }
                off += len + 4;
            }
        }

        this.ws = ws;
        return this;
    },
    receive: function(command, data) {
        var func = Route[command]
        var str = 'Resp.' + func
        data.game = this;
        if (func) {
            if (typeof(eval(str)) == 'function') {
                eval("Resp." + func + "(data)")
            } else {
                this.log(func);
            }
        } else {
            this.log('func validate');
        }
        this.log('websocket received');
        this.log(command);
        this.log(data);
    },
    send: function(code, command, data) {
        this.log('start send data');
        this.log(data);
        if (this.ws.readyState == this.ws.OPEN) {
            this.ws.send(Packet.pack({
                'code': code,
                'command': command,
                'user': User.getUser(),
                'data': data,
            }));
        }
    },
    renderUsers: function(data) {
        var left, right, my;
        var myidx = 0;
        $.each(users, function(idx, user){
            if (data.user.id == user.id) {
                myidx = idx;
                return;
            }
        });
        len = 3;
        my = data.users[myidx];
        right = data.users[(myidx + 1) % len] || undefined
        left = data.users[(myidx + 2) % len] || undefined
        
        if (my) {
            $('#table-my .nickname').text(my.nickname + (my.master ? '(地主)' : '') + (my.current ? ' - 请出牌' : ''));
        }
        
        if (left) {
            $('#table-left .nickname').text(left.nickname + (left.master ? '(地主)' : '') + (left.current ? ' - 正在出牌' : ''));
            var left_container = $('#table-left .cards').empty();
            for (var i=0; i<left.hand_count; i++) {
                left_container.append('<div class="card"></div>');
            }
            $('.card:last', left_container).addClass('last');
        }
        if (right) {
            $('#table-right .nickname').text(right.nickname + (right.master ? '(地主)' : '') + (right.current ? ' - 正在出牌' : ''));
            var right_container = $('#table-right .cards').empty();
            for (var i=0; i<right.hand_count; i++) {
                right_container.append('<div class="card"></div>');
            }
            $('.card:last', right_container).addClass('last');
        }
    },
    renderHoles: function(holes) {
        this.holes = holes;
        var hole_container = $('#table-hole .cards').empty();
        $.each(holes, function(idx, card){
            var item = $('<div class="card">'+ poker.cardShow(card) +'<div>');
            item.data('value', card);
            hole_container.append(item);
        });
    },
    renderHands: function(hands) {
        var my_container = $('#table-my .cards').empty();
        $.each(hands, function(idx, card){
            var item = $('<div class="card">'+ poker.cardShow(card) +'</div>');
            item.data('value', card).data('choosed', false);
            my_container.append(item);
        });
    },
    renderOuts: function(outs) {
        this.outs = outs
        var out_container = $('#table-outs .cards').empty();
        $.each(outs, function(idx, card){
            var item = $('<div class="card">'+ poker.cardShow(card) +'</div>');
            item.data('value', card);
            out_container.append(item);
        });
    }
}